<script>
import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin';
import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";
import {getGoodsList, getShopTypeList, getPointsExchangeRatio, getProductTagGroup} from '@/api/mall.js';
import {getUserIntegral} from '@/api/homePage.js';
import { mapState } from 'vuex';
import { integral } from "./config"
import slFilter from "@/mall_subpages/components/sl-filter/sl-filter.vue";

export default {
  name: "integral",
  components: { HzSafeArea, slFilter },
  mixins: [ZPMixin],
  data() {
    return {
      loading: true,
      pointsProducts: [],
      filterList: [],
      categoryList: [],
      searchParams: {
        ShowPrice: undefined,
        ProductCategoryId: undefined
      },
      IsDesc: {},
      pointsRatio: 1, // 积分兑换比例
      userPoints: 0, // 用户积分
      curSection: '',
      sectionBtns:[
        {
          title:'我能兑换',
          key: '1',
          active:false
        },
        {
          title:'1积分',
          key: '2',
          active:false
        }
      ]
    }
  },
  watch: {
    '$i18n.locale'() {
      // 监听语言变化，重新设置导航栏标题
      this.setNavigationTitle();
      // 更新按钮文本
      this.updateSectionBtns();
    },
  },
  computed: {
    ...mapState({
      userInfo: state => state.base.userInfo,
      safeAreaTop: state => state.app.wxMenuClient.top
    }),
    productList() {
      if (!this.curSection) return this.pointsProducts;
      const resList = this.pointsProducts.filter(item => {
        const points = Math.ceil(item.ShowPrice * this.pointsRatio);
        if (this.curSection === '1') return this.userPoints >= points;
        if (this.curSection === '2') return points === 1;
      })
      return resList;
    }
  },
  onLoad() {
    // 设置导航栏标题
    this.setNavigationTitle();
    // 初始化按钮文本
    this.updateSectionBtns();
    this.init();
    // 获取积分兑换比例
    this.getPointsRatio();
    // 获取用户积分
    this.getUserPoints();
  },
  methods: {
    // 初始化
    async init() {
      try {
        // 初始化筛选数据
        this.initFilterData()
        this.loadCategoryList()
      } catch (error) {
        console.error("初始化错误:", error);
      }

    },

    // 获取积分兑换比例
    async getPointsRatio() {
      try {
        const res = await getPointsExchangeRatio();
        const data = res.Data;
        this.pointsRatio = data.PointToCNYRatio;
        console.log('获取到积分比例:', this.pointsRatio);
      } catch (error) {
        console.error('获取积分比例失败:', error);
        this.pointsRatio = 1;
      }
    },

    // 获取用户积分
    async getUserPoints() {
      try {
        const res = await getUserIntegral();
        if (res && res.Data) {
          this.userPoints = res.Data;
          console.log('获取到用户积分:', this.userPoints);
        }
      } catch (error) {
        console.error('获取用户积分失败:', error);
        this.userPoints = 0;
      }
    },

    // 加载商品分类
    async loadCategoryList() {
      try {
        const res = await getProductTagGroup({
          Index: 1,
          Size: 50,
          ParentId: 1,
          FiledOrder: "Sort asc"
        });

        if (res && res.Data) {
          this.categoryList = res.Data.map(item => {
            return {
              title: item.Name,
              id: item.Id,
              img: item.ImgUrl
            };
          });
        }
      } catch (error) {
        console.error("加载商品分类失败:", error);
      }
    },

    // 分页加载积分产品
    async queryList(pageNo, pageSize) {
      try {
        this.loading = true;
        const { Data } = await getGoodsList({
          Index: pageNo,
          Size: pageSize,
          PurchaseMethod: "1,2",
          ...this.searchParams
        });
        
        // 完成加载
        this.$refs.paging.complete(Data || []);
      } catch (error) {
        console.error("获取积分商品失败:", error);
        this.$refs.paging.complete(false);
      } finally {
        this.loading = false;
      }
    },

    initFilterData(){
      try {
        this.filterList = integral

        getShopTypeList({
          Index: 1,
          Size: 50,
          WhereList: [{
            Name: 'Id',
            Type: 'EqualTo',
            Value: 2028,
          }]
        }).then(res =>{
          const data = res.Data[0].ProductCategoryList.map(item =>{
            return {
              title: item.Name,
              value: item.Id
            }
          })

          data.unshift({
            title: "全部分类",
            value: ""
          })

          this.filterList[3].detailList = data
          // 设置筛选配置
          // this.filterList = integral
        })
      } catch (error) {
        console.error('初始化筛选数据失败:', error)
        uni.showToast({
          title: '加载筛选数据失败',
          icon: 'none'
        })
      }
    },

    // 跳转到积分明细
    goToPointsDetail() {
      uni.navigateTo({
        url: '/user_subpages/vip/integral'
      });
    },
    
    // 商品详情
    goToProductDetail(item) {
      const typeMap = {
        3: '6',
        11: '2',
        12: '3',
        13: '4',
        15: '5'
      };
      const url = typeMap[item.Type]
        ? `/mall_subpages/goods/index?id=${item.Id}&type=${typeMap[item.Type]}&integral=true`
        : `/mall_subpages/mall/detail?id=${item.Id}&type=1&integral=true`;
      uni.navigateTo({ url });
    },
    
    // 交换更多积分
    goToExchangeMore() {
      uni.navigateTo({
        url: '/pages/my/index'
      });
    },
    onSortItem(item, sort) {
      if (item.key) {
        if (item.key === 'default') {
          this.searchParams = {};
        } else {
          this.IsDesc[item.key] = sort;
          this.searchParams.FiledOrder = `${item.key} ${sort}`;
        }
      } else {
        const [type, value] = Object.entries(item)[0];
        this.searchParams[type] = value;
      }
      this.$refs.paging.reload();
    },
    jumpZone(data){
      uni.navigateTo({
        url: `/mall_subpages/mall/integralZone?id=${data.id}&title=${data.title}`
      })
    },
    jumpPointsMall(){
      uni.navigateTo({
        url: "/user_subpages/vip/integral"
      })
    },
    jumpFavor() {
      const url = '/user_subpages/collection/collection';
      uni.navigateTo({ url });
    },
    jumpOrder(){
      uni.switchTab({
        url: '/pages/order/index',
        success: () => {
          this.$store.commit('setCurrent', 3);
        }
      })
    },
    sectionBtnClick(item){
      if (item.key === this.curSection && item.active) {
        item.active = false;
        this.curSection = '';
      } else {
        this.curSection = item.key;
        this.sectionBtns.forEach(item => {
          item.active = false;
        })
        item.active = true;
      }
      this.$refs.paging.reload();
    },

    // 设置导航栏标题
    setNavigationTitle() {
      uni.setNavigationBarTitle({
        title: this.$t('mall.integral.title')
      });
    },

    // 更新按钮文本
    updateSectionBtns() {
      this.sectionBtns = [
        {
          title: this.$t('mall.integral.canExchange'),
          key: '1',
          active: false
        },
        {
          title: this.$t('mall.integral.onePoint'),
          key: '2',
          active: false
        }
      ];
    },
    hiddenItem(item) {
      if (!this.curSection) return false;
      const points = Math.ceil(item.ShowPrice * this.pointsRatio);
      if (this.curSection === '1') return this.userPoints < points;
      return points !== 1;
    },
    goSignIn(){
      uni.navigateTo({
        url:'/user_subpages/userCenter/registration'
      })
    },
    jumpCoupons() {
      const url = '/user_subpages/vip/coupon?from=integral';
      uni.navigateTo({ url });
    },
  }
}
</script>

<template>
  <z-paging
    ref="paging"
    v-model="pointsProducts"
    @query="queryList"
    refresher-background="#f5f5f5"
    :show-scrollbar="false"
  >
    <template #top>
      <!-- 顶部背景区域 -->
      <view class="header-bg">
        <!-- 导航栏使用u-navbar替代红框标注的部分 -->
        <u-navbar :title="$t('mall.integral.title')"
                  :titleStyle="{color: '#000'}"
                  :autoBack="true"
                  bgColor="transparent"
                  :fixed="false"
                  left-icon-color="#606266"></u-navbar>
        
        <!-- 用户积分信息 -->
        <view class="user-points">
          <view class="points-text" @click="jumpPointsMall">
          <image class="user-points-image" src="./img/jifen.png" mode="widthFix"></image>
            {{$t('mall.integral.points')}}: {{userPoints || 0}} <text class="points-more" @click="goToExchangeMore">></text>
          </view>
                    <view class="action-btns">
             <view class="action-btn" @click="jumpFavor">{{$t('mall.integral.favorites')}}</view>
             <view class="action-btn" @click="jumpOrder">{{$t('mall.integral.orders')}}</view>
           </view>
        </view>
      </view>
    </template>

    <!-- 热门推荐区域 -->
    <view class="recommend-section">
      <view class="section-title">{{$t('mall.integral.hotRecommend')}}</view>
      <view class="recommend-items">
        <!-- 第一个商品 - 单独占一行 -->
        <view class="recommend-item large" @click="jumpZone(categoryList[0])">
          <image :src="categoryList[0].img" class="recommend-image"></image>
<!--          <view class="recommend-content">-->
<!--            <view class="recommend-name">小镇东西 →</view>-->
<!--          </view>-->
        </view>
        
        <!-- 右侧两个商品 - 并排显示 -->
        <view class="recommend-right">
          <!-- CPI生日季 -->
          <view class="recommend-item small" @click="goSignIn(categoryList[1])">
            <image :src="categoryList[1].img" class="recommend-image"></image>
<!--            <view class="recommend-content">-->
<!--              <view class="recommend-title">CPI生日季</view>-->
<!--              <view class="recommend-btn">立即抢</view>-->
<!--            </view>-->
          </view>
          
          <!-- 最近上新 -->
          <view class="recommend-item small mint" @click="jumpCoupons">
            <image :src="categoryList[2].img" class="recommend-image"></image>
<!--            <view class="recommend-content">-->
<!--              <view class="recommend-title">最近上新</view>-->
<!--              <view class="recommend-subtitle">新品抢先尝</view>-->
<!--              <view class="recommend-btn">立即抢</view>-->
<!--            </view>-->
          </view>
        </view>
      </view>
    </view>

    <!-- 积分兑换区域 -->
    <view class="exchange-section">
      <view class="section-header">
        <view class="section-title">{{$t('mall.integral.pointsExchange')}}</view>
        <sl-filter
          :independence="true"
          :topFixed="false"
          :tab-height="34"
          titleColor="#333"
          :isDesc="IsDesc"
          themeColor="#dab34c"
          :menuList.sync="filterList"
          style="flex: 1"
          @onSortItem="onSortItem"
        />

        <view class="section-btns">
          <view
            v-for="item in sectionBtns"
            :key="item.key"
            class="section-btn"
            :class="{active:item.active}"
            @click="sectionBtnClick(item)"
          >
            {{ item.title }}
          </view>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="product-grid">
        <view
          class="product-item"
          v-for="(item, index) in productList"
          :key="index"
          @click="goToProductDetail(item)"
        >
          <view class="product-image">
            <image class="bg-img" src="./img/moban.png" mode="widthFix"></image>
            <image :src="item.Img || ''" mode="aspectFill"></image>
          </view>
          <view class="product-info">
            <view class="product-title">{{item.Name || '商品名称'}}</view>
            <view class="product-price">
              <text class="price-value">{{item.Points || (item.ShowPrice ? Math.ceil(item.ShowPrice * pointsRatio) : 0)}}</text>
              <text class="price-unit">{{$t('mall.integral.pointsUnit')}}</text>
              <text class="price-original" v-if="item.OriginalPrice">¥{{item.OriginalPrice}}</text>
            </view>
          </view>
          <view class="exchange-time" v-if="item.ExchangeTime">
            {{item.ExchangeTime}}
          </view>
        </view>
      </view>
    </view>

    <hz-safe-area></hz-safe-area>
  </z-paging>
</template>

<style scoped lang="scss">
// 顶部背景
.header-bg {
  position: relative;
  // height: 260rpx;
  //background-color: #333333;
  background-image: url('https://wzws.wanshanlundiao.cn/upload/img/ws_static/static/jfsc/jfsc.png');
  background-repeat: no-repeat;
  background-size: cover;
  
  .user-points {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    height: 180rpx;
    
    .points-text {
      font-size: 30rpx;
      // font-weight: bold;
      color: #000;
      display: flex;
      align-items: center;

      .user-points-image{
        width: 60rpx;
        margin-right: 10rpx;
      }
      
      .points-more {
        margin-left: 10rpx;
        font-size: 24rpx;
      }
    }
    
    .action-btns {

      display: flex;
      gap: 20rpx;
      
      .action-btn {
        background: #333333;
        border-radius: 46rpx;
        padding: 10rpx 30rpx;
        font-size: 24rpx;
        color: #fff;
      }
    }
  }
}

// 热门推荐区域
.recommend-section {
  padding: 30rpx;
  background: #fff;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    line-height: 48rpx;
    color: #27282E;
    margin-bottom: 18rpx;
    position: relative;
    display: inline-block;
    padding-bottom: 10rpx; 
    &::before {
      content: '';
      position: absolute;
      left: 20rpx;
      bottom: 6rpx;
      width: 100rpx;
      height: 20rpx;
      background-image: url('./img/tabBj.png');
      background-repeat: no-repeat;
      background-size: cover;
      background-position: center;
      opacity: .6;
      transform: rotate(-7deg);
    }
  }
  
  .recommend-items {
    display: flex;
    flex-wrap: wrap;
    height: 360rpx;
    gap: 20rpx;
    
    .large {
      flex: 1;
      height: 100%;
      
      .recommend-name {
        position: absolute;
        left: 20rpx;
        bottom: 20rpx;
        font-size: 28rpx;
        color: #333;
        background-color: rgba(255, 228, 189, 0.8);
        padding: 10rpx 20rpx;
        border-radius: 5rpx;
      }
    }
    
    .recommend-right {
      display: flex;
      flex-direction: column;
      flex: 1;
      gap: 20rpx;
      
      .small {
        flex: 1;
        height: 180rpx;
      }
    }
    
    .recommend-item {
      background-color: #fff;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
      
      .recommend-image {
        width: 100%;
        height: 100%;
        background-color: #f0f0f0;
      }
      
      .recommend-content {
        position: absolute;
        bottom: 20rpx;
        left: 20rpx;
        right: 20rpx;
        
        .recommend-title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .recommend-subtitle {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 10rpx;
        }
        
        .recommend-btn {
          display: inline-block;
          background-color: #1e1e1e;
          color: #fff;
          font-size: 22rpx;
          padding: 6rpx 20rpx;
          border-radius: 30rpx;
        }
      }
    }
  }
}

// 麓豆兑换区域
.exchange-section {
  padding: 0 30rpx 30rpx;
  
  .section-header {
    margin-bottom: 30rpx;

    .filterItems{
      display: flex;
      align-items: center;

      .reset{
        padding: 0 60rpx 0 30rpx;
        font-size: 26rpx;
        height: 100%;
      }
    }
    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      line-height: 48rpx;
      color: #27282E;
      margin-bottom: 18rpx;
      position: relative;
      display: inline-block;
      padding-bottom: 10rpx; 
      &::before {
        content: '';
        position: absolute;
        left: 20rpx;
        bottom: 6rpx;
        width: 100rpx;
        height: 20rpx;
        background-image: url('./img/tabBj.png');
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center;
        opacity: .6;
        transform: rotate(-7deg);
      }
    }
    
    .filter-options {
      display: flex;
      margin-bottom: 20rpx;
      
      .filter-item {
        margin-right: 30rpx;
        font-size: 26rpx;
        color: #999;
        
        &.active {
          color: #D4AF7A;
          font-weight: bold;
        }
        
        .sort-arrow {
          font-size: 20rpx;
        }
      }
      
      .filter-more {
        margin-left: auto;
        margin-right: 0;
      }
    }
    
    .exchange-status {
      display: flex;
      margin-bottom: 20rpx;
      
      .status-item {
        font-size: 24rpx;
        color: #666;
        margin-right: 20rpx;
      }
      
      .status-value {
        font-size: 24rpx;
        color: #D4AF7A;
      }
    }
  }

  .section-btns{
    margin-top: 20rpx;
    display: flex;
    justify-content: left;
    align-items: center;
    font-size: 24rpx;

    .section-btn{
      background: #F7F8FA;
      border-radius: 28rpx;
      padding: 4rpx 20rpx;
      margin-right: 20rpx;
      color: #333;
    }

    .active{
      color: #00ACF4;
      background: rgba(27, 29, 30, 0.05);
    }
  }
  
  // 商品网格
  .product-grid {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10rpx;
    
    .product-item {
      width: calc(50% - 20rpx);
      margin: 0 10rpx 30rpx;
      background-color: #fff;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
      
      .product-image {
        position: relative;

        .bg-img{
          position: absolute;
          left: 0;
          bottom: 0;
          top: 0;
        }

        image{
          width: 100%;
          height: 342rpx;
          border-radius: 10rpx;
          &:last-child{
            height: 334rpx;
            border-radius: 18rpx;
          }
        }
      }
      
      .product-info {
        padding: 20rpx 10rpx;
        .product-title {
          font-size: 28rpx;
          color: #27282E;
          margin-bottom: 10rpx;
        }
        
        .product-price {
          display: flex;
          align-items: baseline;
          
          .price-value {
            font-size: 30rpx;
            color: #FF6B0D;
            font-weight: bold;
          }
          
          .price-unit {
            font-size: 24rpx;
            color: #90949C;
            margin-left: 5rpx;
          }
          
          .price-original {
            font-size: 22rpx;
            color: #999;
            text-decoration: line-through;
            margin-left: 20rpx;
          }
        }
      }
      
      .exchange-time {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #FFE4BD;
        color: #D4AF7A;
        text-align: center;
        font-size: 24rpx;
        padding: 10rpx;
      }
    }
  }
}
</style>